package com.king.oa.util;

import org.apache.struts2.ServletActionContext;

import com.king.oa.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class CheckPrivilegeInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -8561547685866664646L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		String ipaddr = ServletActionContext.getRequest().getRemoteAddr();
		//若是外网ip则拒绝访问
		if(!CheckLAN.isLAN(ipaddr)){
			return "noPrivilegeError";
		}
		
		
		//获取信息
		User user = (User) ActionContext.getContext().getSession().get("user");
		String namespace = invocation.getProxy().getNamespace();
		String actionName = invocation.getProxy().getActionName();
		String privUrl = namespace + actionName;
		
		//验证是否登录
		if(user == null){//未登录，转到登录页面
			//若是正在登录，则直接放行
			if(privUrl.equals("/user_login")){
				return invocation.invoke();
			}
			return "loginUI";
		}else{//已登录，判断权限
			
			if(user.getName().equals("admin")){
				return invocation.invoke();
			}
			
			if(user.hasPrivilegeByUrl(privUrl)){
				//->有权限则放行
				return invocation.invoke();
			}else{
				//->没有权限，转到提示页面
				return "noPrivilegeError";
			}
		}
		
	}


}
